"use client"

import { useState, useEffect } from 'react'
import { resetDatabase } from '@/lib/data'
import { 
  Card, 
  CardContent, 
  CardDescription, 
  CardHeader, 
  CardTitle 
} from '@/components/ui/card'
import { 
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import { useToast } from '@/components/ui/use-toast'
import Login from '@/components/admin/login'
import { AlertTriangle, Database, Save, Shield, LayoutDashboard, Paintbrush } from 'lucide-react'

export default function SettingsPage() {
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [resetDialogOpen, setResetDialogOpen] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [settings, setSettings] = useState({
    enableDarkMode: true,
    allowRegistration: false,
    manualApproval: true,
    autoBackup: true,
    logActions: true,
    enableNotifications: false
  })
  const { toast } = useToast()
  
  // 检查用户是否已经登录
  useEffect(() => {
    const checkAuth = () => {
      // 先检查session storage
      const sessionAuth = sessionStorage.getItem('admin_auth')
      // 再检查local storage
      const localAuth = localStorage.getItem('admin_auth')
      
      if (sessionAuth || localAuth) {
        setIsAuthenticated(true)
      }
      
      setIsLoading(false)
    }
    
    // 由于涉及到localStorage和sessionStorage，
    // 需要在客户端渲染后执行
    checkAuth()
  }, [])

  const handleLoginSuccess = () => {
    setIsAuthenticated(true)
  }

  const handleResetDatabase = async () => {
    try {
      await resetDatabase()
      setResetDialogOpen(false)
      
      toast({
        title: "重置成功",
        description: "数据库已成功重置",
      })
    } catch (err: any) {
      console.error('重置数据库失败:', err)
      setError('重置数据库失败，请稍后重试')
      
      toast({
        variant: "destructive",
        title: "重置失败",
        description: "数据库重置操作失败，请稍后重试",
      })
    }
  }

  const updateSetting = (key: string, value: boolean) => {
    setSettings(prev => ({
      ...prev,
      [key]: value
    }))
  }

  const saveSettings = () => {
    // 这里应该是将设置保存到服务器的逻辑
    // 但在这个示例中，我们只是模拟一个成功的保存操作
    toast({
      title: "设置已保存",
      description: "您的系统设置已成功更新",
    })
  }

  // 加载中状态
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[calc(100vh-130px)]">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mb-4"></div>
          <p className="text-gray-400">正在加载...</p>
        </div>
      </div>
    )
  }

  // 如果未认证，显示登录表单
  if (!isAuthenticated) {
    return <Login onLoginSuccess={handleLoginSuccess} />
  }

  // 已认证，显示系统设置界面
  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-2xl font-bold tracking-tight">系统设置</h2>
        
        <Button 
          onClick={saveSettings}
          className="flex items-center gap-2"
        >
          <Save className="h-4 w-4" />
          保存设置
        </Button>
      </div>
      
      {error && (
        <div className="p-4 rounded-lg bg-red-950 border border-red-800 text-red-200">
          <div className="flex items-center gap-2 mb-2">
            <AlertTriangle className="h-5 w-5" />
            <h3 className="font-semibold">错误</h3>
          </div>
          <p>{error}</p>
        </div>
      )}
      
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* 用户设置 */}
        <Card className="border border-gray-800 bg-[#1a1d24]">
          <CardHeader className="flex flex-row items-center gap-2">
            <Shield className="h-5 w-5 text-blue-500" />
            <div>
              <CardTitle>用户和权限</CardTitle>
              <CardDescription>管理用户访问和权限设置</CardDescription>
            </div>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label htmlFor="allowRegistration">允许新用户注册</Label>
                <p className="text-sm text-gray-500">启用后，新用户可以自行注册账号</p>
              </div>
              <Switch 
                id="allowRegistration" 
                checked={settings.allowRegistration}
                onCheckedChange={(checked) => updateSetting('allowRegistration', checked)}
              />
            </div>
            
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label htmlFor="manualApproval">手动审核新用户</Label>
                <p className="text-sm text-gray-500">启用后，新用户需要管理员手动审核</p>
              </div>
              <Switch 
                id="manualApproval" 
                checked={settings.manualApproval}
                onCheckedChange={(checked) => updateSetting('manualApproval', checked)}
                disabled={!settings.allowRegistration}
              />
            </div>
            
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label htmlFor="logActions">记录用户操作</Label>
                <p className="text-sm text-gray-500">记录管理员的所有操作日志</p>
              </div>
              <Switch 
                id="logActions" 
                checked={settings.logActions}
                onCheckedChange={(checked) => updateSetting('logActions', checked)}
              />
            </div>
          </CardContent>
        </Card>

        {/* 界面设置 */}
        <Card className="border border-gray-800 bg-[#1a1d24]">
          <CardHeader className="flex flex-row items-center gap-2">
            <Paintbrush className="h-5 w-5 text-green-500" />
            <div>
              <CardTitle>界面设置</CardTitle>
              <CardDescription>自定义系统的外观和布局</CardDescription>
            </div>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label htmlFor="enableDarkMode">默认启用深色模式</Label>
                <p className="text-sm text-gray-500">设置系统默认使用深色主题</p>
              </div>
              <Switch 
                id="enableDarkMode" 
                checked={settings.enableDarkMode}
                onCheckedChange={(checked) => updateSetting('enableDarkMode', checked)}
              />
            </div>
            
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label htmlFor="enableNotifications">启用通知</Label>
                <p className="text-sm text-gray-500">允许系统发送通知消息</p>
              </div>
              <Switch 
                id="enableNotifications" 
                checked={settings.enableNotifications}
                onCheckedChange={(checked) => updateSetting('enableNotifications', checked)}
              />
            </div>
          </CardContent>
        </Card>
      </div>
      
      {/* 系统管理 */}
      <Card className="border border-gray-800 bg-[#1a1d24]">
        <CardHeader className="flex flex-row items-center gap-2">
          <LayoutDashboard className="h-5 w-5 text-yellow-500" />
          <div>
            <CardTitle>系统管理</CardTitle>
            <CardDescription>数据库和系统维护操作</CardDescription>
          </div>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label htmlFor="autoBackup">自动备份数据</Label>
              <p className="text-sm text-gray-500">每天自动备份系统数据</p>
            </div>
            <Switch 
              id="autoBackup" 
              checked={settings.autoBackup}
              onCheckedChange={(checked) => updateSetting('autoBackup', checked)}
            />
          </div>
          
          <div className="border border-red-900 bg-red-950/20 rounded-lg p-4 mt-4">
            <h3 className="text-lg font-medium mb-2 text-red-300 flex items-center gap-2">
              <AlertTriangle className="h-5 w-5" />
              危险区域
            </h3>
            <p className="text-gray-400 mb-4">
              以下操作可能会导致数据丢失，请谨慎操作。
            </p>
            <Button 
              variant="destructive" 
              onClick={() => setResetDialogOpen(true)}
              className="flex items-center gap-2 bg-red-700 hover:bg-red-800"
            >
              <Database className="h-4 w-4" />
              重置数据库
            </Button>
          </div>
        </CardContent>
      </Card>
      
      {/* 重置数据库确认对话框 */}
      <AlertDialog open={resetDialogOpen} onOpenChange={setResetDialogOpen}>
        <AlertDialogContent className="bg-[#1a1d24] border-gray-800 text-white">
          <AlertDialogHeader>
            <AlertDialogTitle>确认重置数据库?</AlertDialogTitle>
            <AlertDialogDescription className="text-gray-400">
              此操作将清空所有玩家数据，该操作无法撤销。确定要继续吗？
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="bg-transparent border-gray-700 hover:bg-gray-800 hover:text-white">
              取消
            </AlertDialogCancel>
            <AlertDialogAction 
              onClick={handleResetDatabase}
              className="bg-red-600 hover:bg-red-700 text-white focus:ring-red-600"
            >
              确认重置
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
} 